package com.hsy.crm.web.web.report;

import com.hsy.crm.web.domain.cm.App;
import com.hsy.crm.web.domain.ex.ActionException;
import com.hsy.crm.web.domain.po.product.ProductExportPo;
import com.hsy.crm.web.domain.vo.report.ExcelVo;
import com.hsy.crm.web.service.impl.excel.EProductService;
import com.hsy.crm.web.web.BaseAction;
import com.hsy.crm.web.domain.cm.App;
import com.hsy.crm.web.domain.ex.ActionException;
import com.hsy.crm.web.domain.po.product.ProductExportPo;
import com.hsy.crm.web.domain.vo.report.ExcelVo;
import com.hsy.crm.web.web.BaseAction;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eexport")
public class ExcelExportAction extends BaseAction {

    @Autowired
    EProductService eproductService;

    @RequestMapping("/product")
    public void exportProduct(HttpServletRequest request, HttpServletResponse response, ExcelVo excelVo) {

        String fileName = "商品列表.xlsx";
        response.setHeader("Content-Disposition", "attachment; filename="+getFileName(request,fileName));
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");

        String templatePath = App.Config.EXCEL_TEMPLATE_DIR + "product.xlsx";
        List<ProductExportPo> productData = eproductService.findProductData(excelVo);
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new BufferedInputStream(new FileInputStream(templatePath));
            Workbook workbook = getWorkbook(in, productData);
            out = response.getOutputStream();
            //将内容写入输出流并把缓存的内容全部发出去
            workbook.write(out);
            out.flush();
        } catch (InvalidFormatException e) {
            throw new ActionException(e);
        } catch (IOException e) {
            throw new ActionException(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
    }

    private static Workbook getWorkbook(InputStream in, Object data) throws InvalidFormatException {
        XLSTransformer transformer = new XLSTransformer();
        return transformer.transformXLS(in, getBeansMap(data));
    }

    private static Map<String, Object> getBeansMap(Object data) {
        Map<String, Object> beans = new HashMap<String, Object>();
        beans.put("data", data);
        return beans;
    }

    private static String getFileName(HttpServletRequest request,String fileName){
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.toUpperCase().contains("MOZILLA") ||
                userAgent.toUpperCase().contains("CHROME")) {
            try{
                fileName = new String(fileName.getBytes(), "ISO-8859-1");
            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
        } else {
            try{
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
        }
        return fileName;
    }

}
